const db_promise = require("../config/db.config.js");
const logger = require('../util/logger');

async function getBotRegex(req, res, next) {
  logger.winston.info('regex.getBotRegex');
  
  try {
    	
    	 const [rows,fields] = await db_promise.query("select * from regex where bot_id = ? order by regex_id desc",[req.params.bot_id]);
    	 res.status(200).json(rows);
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  }     
  
}

async function getSingleRegex(req, res, next) {
  logger.winston.info('regex.getSingleRegex');
  
  try {
    	
    	 const [rows,fields] = await db_promise.query("select * from regex where regex_id = ?",[req.params.regex_id]);
    	 if (rows.length >= 1){
    	 	   rows_one = rows[0];
    	 }
    	 
    	 res.status(200).json(rows_one);   
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  }   
  
}

async function createRegex(req, res, next) {
  logger.winston.info('regex.createRegex');

  
    try {
    	
			  const [rows,fields] = await db_promise.query("insert into regex(bot_id, regex_name, regex_pattern) values (?,?,?)", [req.body.bot_id, req.body.regex_name, req.body.regex_pattern]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }    
  
  
}

async function updateRegex(req, res, next) {
  logger.winston.info('regex.updateRegex');
  
  
    try {
    	
			  const [rows,fields] = await db_promise.query("update regex set regex_name = ?, regex_pattern = ? where regex_id = ?", [req.body.regex_name, req.body.regex_pattern, req.body.regex_id]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }     
  
}

async function removeRegex(req, res, next) {
  logger.winston.info('regex.removeRegex');

  
  
    try {
    	
			  const [rows,fields] = await db_promise.query("delete from regex where regex_id = ?", [req.body.regex_id]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }    
    
  
}

module.exports = {
  getBotRegex,
  getSingleRegex,
  createRegex,
  updateRegex,
  removeRegex};
